package test.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 结合 Spring 进行 FreeMarker 配置
 * 
 * @author hemj
 * @date 2017年1月11日
 */
@Controller
@RequestMapping("/test")
public class SpringFreeMarker {
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	@RequestMapping("/welcome")
	public void test(HttpServletResponse resp) {
		try {
			// 模版配置对象
			Configuration cfg = freeMarkerConfigurer.getConfiguration();

			// 创建模版对象
			Template t = cfg.getTemplate("test.html", Locale.CHINA);

			// 创建模板参数
			Map map = new HashMap();
			map.put("user", "musesoft");
			map.put("url", "http://www.baidu.com/");
			map.put("name", "百度");

			// 输出内容到指定的输出流中
			resp.setCharacterEncoding("UTF-8");
			Writer os = resp.getWriter();
			t.process(map, os);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
